# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(plyr)
library(gridExtra)
library(scales)
library(egg)
library(VennDiagram)
library(optparse)
library(tidyverse)
library(magrittr)
library(plotrix)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
)
opt <- parse_args(OptionParser(option_list = option_list))

getClassCols <- function(n){
    inCols <- c("#00FFFF", "#0099FF", "#8A4198", "#FF6F00", "#CC9999", "#FFFF00", "#00FF7F", "#999999", "#CCFFCC", "#336666",
    "#FF6666", "#FFCC33", "#CC3399")
    extraColors <- c("#CD0000", "#3A89CC", "#769C30", "#D99536", "#7B0078", "#BFBC3B", "#6E8B3D", "#00688B", "#C10077", "#CAAA76",
    "#EEEE00", "#458B00", "#8B4513", "#008B8B", "#6E8B3D", "#8B7D6B", "#7FFF00", "#CDBA96", "#ADFF2F")
    orignalCols <- c(inCols, extraColors)
    on <- length(orignalCols)
    if (n <= on) {
        orignalCols[1 : n]
    }else {
        ggCols <- gg_color_hue(n - on)
        c(orignalCols, ggCols)
    }
}

flower_plot <- function(sample, otu_num, core_otu, start, a, b, r, ellipse_col, circle_col) {
    par(bty = 'n', ann = F, xaxt = 'n', yaxt = 'n', mar = c(1, 1, 1, 1))
    plot(c(0, 10), c(0, 10), type = 'n')
    n <- length(sample)
    deg <- 360 / n
    res <- lapply(1 : n, function(t){
        draw.ellipse(x = 5 + cos((start + deg * (t - 1)) * pi / 180),
        y = 5 + sin((start + deg * (t - 1)) * pi / 180),
        col = ellipse_col[t],
        border = ellipse_col[t],
        a = a, b = b, angle = deg * (t - 1))
        text(x = 5 + 2.5 * cos((start + deg * (t - 1)) * pi / 180),
        y = 5 + 2.5 * sin((start + deg * (t - 1)) * pi / 180),
        otu_num[t])

        if (deg * (t - 1) < 180 && deg * (t - 1) > 0) {
            text(x = 5 + 3.3 * cos((start + deg * (t - 1)) * pi / 180),
            y = 5 + 3.3 * sin((start + deg * (t - 1)) * pi / 180),
            sample[t],
            srt = deg * (t - 1) - start,
            adj = 1,
            cex = 1
            )
        } else {
            text(x = 5 + 3.3 * cos((start + deg * (t - 1)) * pi / 180),
            y = 5 + 3.3 * sin((start + deg * (t - 1)) * pi / 180),
            sample[t],
            srt = deg * (t - 1) + start,
            adj = 0,
            cex = 1
            )
        }
    })
    draw.circle(x = 5, y = 5, r = r, col = circle_col, border = NA)
    text(x = 5, y = 5, paste('Core:', core_otu))
}

plotEmptyPage <- function(pdfFileName){
    p <- ggplot() + theme_void()
    ggsave(limitsize = FALSE,pdfFileName, p, width = 8, height = 8)
}
plotEmptyPageAndExit <- function(pdfFileName){
    plotEmptyPage(pdfFileName)
    quit(status = 0)
}
closeAndPlotEmptyPageAndExit <- function(pdfFileName){
    dev.off()
    plotEmptyPageAndExit(pdfFileName)
}

vennPlot <- function(datas){
    margin <- 0.1
    if (size == 1) {
        data1 <- datas[1] %>%
        unlist()
        area = length(data1)
        tryCatch(draw.single.venn(area = area, fill = c("#4040FF"),
        category = treatsStr, cat.default.pos = "text",
        cat.cex = 2, cex = 2, lty = "blank", alpha = 0.5
        ), error = function(e){
            closeAndPlotEmptyPageAndExit(pdfFileName)
        })
    }else if (size == 2) {
        data1 <- datas[1] %>%
        unlist()
        data2 <- datas[2] %>%
        unlist()
        area1 = length(data1)
        area2 = length(data2)
        crossArea = length(intersect(data1, data2))
        tryCatch(draw.pairwise.venn(area1 = area1, area2 = area2, cross.area = crossArea, fill = c("#4040FF", "#FF4040"),
        category = treatsStr, cat.default.pos = "text",
        cat.cex = 2, cex = c(2, 2, 2), lty = rep("blank", 2), alpha = c(0.5, 0.5), margin = margin
        ), error = function(e){
            closeAndPlotEmptyPageAndExit(pdfFileName)
        })
    }else if (size == 3) {
        data1 <- datas[1] %>%
        unlist()
        data2 <- datas[2] %>%
        unlist()
        data3 <- datas[3] %>%
        unlist()
        area1 <- length(data1)
        area2 <- length(data2)
        area3 <- length(data3)
        n12 <- length(intersect(data1, data2))
        n23 <- length(intersect(data2, data3))
        n13 <- length(intersect(data1, data3))
        n123 <- length(Reduce(intersect, list(data1, data2, data3)))
        draw.triple.venn(area1 = area1, area2 = area2, area3 = area3, n12 = n12, n23 = n23, n13 = n13, n123 = n123,
        cross.area = crossArea, fill = c("#4040FF", "#FF4040", "#00FF00"),
        category = treatsStr, cat.default.pos = "text",
        cat.cex = 2, cex = 2, lty = rep("blank", 3), alpha = 0.5, margin = margin
        )
    }else if (size == 4) {
        data1 <- datas[1] %>%
        unlist()
        data2 <- datas[2] %>%
        unlist()
        data3 <- datas[3] %>%
        unlist()
        data4 <- datas[4] %>%
        unlist()
        area1 <- length(data1)
        area2 <- length(data2)
        area3 <- length(data3)
        area4 <- length(data4)
        n12 <- length(intersect(data1, data2))
        n13 <- length(intersect(data1, data3))
        n14 <- length(intersect(data1, data4))
        n23 <- length(intersect(data2, data3))
        n24 <- length(intersect(data2, data4))
        n34 <- length(intersect(data3, data4))
        n123 <- length(Reduce(intersect, list(data1, data2, data3)))
        n124 <- length(Reduce(intersect, list(data1, data2, data4)))
        n134 <- length(Reduce(intersect, list(data1, data3, data4)))
        n234 <- length(Reduce(intersect, list(data2, data3, data4)))
        n1234 <- length(Reduce(intersect, list(data1, data2, data3, data4)))
        fill <- getClassCols(size)
        draw.quad.venn(area1 = area1, area2 = area2, area3 = area3, area4 = area4, n12 = n12, n13 = n13, n14 = n14, n23 = n23,
        n24 = n24, n34 = n34, n123 = n123, n124 = n124, n134 = n134, n234 = n234, n1234 = n1234, category = treatsStr, cat.default.pos = "text",
        cat.cex = 2, cex = 2, lty = "blank", alpha = 0.5, fill = fill, margin = margin
        )
    }else if (size == 5) {
        data1 <- datas[1] %>%
        unlist()
        data2 <- datas[2] %>%
        unlist()
        data3 <- datas[3] %>%
        unlist()
        data4 <- datas[4] %>%
        unlist()
        data5 <- datas[5] %>%
        unlist()
        area1 <- length(data1)
        area2 <- length(data2)
        area3 <- length(data3)
        area4 <- length(data4)
        area5 <- length(data5)
        n12 <- length(intersect(data1, data2))
        n13 <- length(intersect(data1, data3))
        n14 <- length(intersect(data1, data4))
        n15 <- length(intersect(data1, data5))
        n23 <- length(intersect(data2, data3))
        n24 <- length(intersect(data2, data4))
        n25 <- length(intersect(data2, data5))
        n34 <- length(intersect(data3, data4))
        n35 <- length(intersect(data3, data5))
        n45 <- length(intersect(data4, data5))
        n123 <- length(Reduce(intersect, list(data1, data2, data3)))
        n124 <- length(Reduce(intersect, list(data1, data2, data4)))
        n125 <- length(Reduce(intersect, list(data1, data2, data5)))
        n134 <- length(Reduce(intersect, list(data1, data3, data4)))
        n135 <- length(Reduce(intersect, list(data1, data3, data5)))
        n145 <- length(Reduce(intersect, list(data1, data4, data5)))
        n234 <- length(Reduce(intersect, list(data2, data3, data4)))
        n235 <- length(Reduce(intersect, list(data2, data3, data5)))
        n245 <- length(Reduce(intersect, list(data2, data4, data5)))
        n345 <- length(Reduce(intersect, list(data3, data4, data5)))
        n1234 <- length(Reduce(intersect, list(data1, data2, data3, data4)))
        n1235 <- length(Reduce(intersect, list(data1, data2, data3, data5)))
        n1245 <- length(Reduce(intersect, list(data1, data2, data4, data5)))
        n1345 <- length(Reduce(intersect, list(data1, data3, data4, data5)))
        n2345 <- length(Reduce(intersect, list(data2, data3, data4, data5)))
        n12345 <- length(Reduce(intersect, list(data1, data2, data3, data4, data5)))
        fill <- getClassCols(size)
        draw.quintuple.venn(area1 = area1, area2 = area2, area3 = area3, area4 = area4, area5 = area5, n12 = n12, n13 = n13,
        n14 = n14,
        n15 = n15, n23 = n23, n24 = n24, n25 = n25, n34 = n34, n35 = n35, n45 = n45, n123 = n123, n124 = n124, n125 = n125,
        n134 = n134, n135 = n135, n145 = n145, n234 = n234, n235 = n235, n245 = n245, n345 = n345, n1234 = n1234,
        n1235 = n1235, n1245 = n1245, n1345 = n1345, n2345 = n2345, n12345 = n12345,
        category = treatsStr, cat.default.pos = "text",
        cat.cex = 2, cex = 2, lty = "blank", alpha = 0.5, fill = fill, margin = margin
        )
    }else {
        otu_num <- length(datas)
        core_num <- Reduce(intersect, datas) %>%
        length()
        fill <- getClassCols(size)
        flower_plot(treats, otu_num, core_num, start = 90, a = 0.5, b = 2, r = 1, ellipse_col = fill, circle_col = 'white')
    }
}

workspacePath <- "../../"

dir <- str_c(workspacePath)

dirs <- list.dirs(dir, recursive = F) %>%
keep(~ str_detect(.x, "_vs_"))
treats <- basename(dirs)
size <- length(treats)
datas <- treats %>%
map(function(treat){
    subDir <- str_c(workspacePath, treat, "/cor/01")
    fileParent <- list.dirs(subDir, recursive = F) %>%
        keep(~ str_detect(.x, "_and_")) %>%
        head(1)
    filePath <- str_c(fileParent, "/Network_Nodes_for_Cytoscape.csv")
    data <- read_csv(filePath) %>%
    .$Node
})
treatsStr <- treats %>%
map_chr(~ str_c(.x, "\n"))
pdfFileName <- str_c("Intra_Correlation_Venn_Plot.pdf")
maxCharNum <- treatsStr %>%
  map_dbl(~str_length(.x)) %>%
  max()
width <- 8 + maxCharNum * 1
height <- width
print(height)
pdf(pdfFileName, width = width, height = height)
par(mar = c(2, 0, 2, 6) + 0.1, family = "Times")
vennPlot(datas)
dev.off()








